package ofpof.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ofpof.service.SecurityService;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;

public class SecurityFilter extends OncePerRequestFilter {

	private SecurityService securityService;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		try {
			initSecurityService();
			securityService.tryLoginWithCookies(request,response);
			chain.doFilter(request, response);
		} finally {
			securityService.clearThreadLocal();

		}

	}

	public void initSecurityService() {
		if (securityService == null) {
			WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
			securityService = (SecurityService) wac.getBean("securityService");
		}
	}

}
